<template>
  <div class="word-detail-container">
    <Header :url="userImageUrl" />
      <!-- 返回按钮 -->
    <div class="back-button-container">
      <el-button @click="goBack" type="text" class="back-btn">
        <i class="el-icon-arrow-left"></i>
        <span>返回</span>
      </el-button>
    </div>
    
    <div class="word-detail-content">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <div class="spinner"></div>
        <p>正在查询单词详情...</p>
      </div>
      
      <!-- 错误状态 -->
      <div v-else-if="error" class="error-container">
        <div class="error-icon">⚠️</div>
        <h3>查询失败</h3>
        <p>{{ errorMessage }}</p>
        <el-button @click="retryQuery" type="primary">重试</el-button>
      </div>
      
      <!-- 单词详情 -->
      <div v-else-if="wordData" class="word-detail-panel">        <!-- 单词头部 -->
        <div class="word-header">
          <h1 class="word-text">{{ wordData.word }}</h1>
          <!-- 单词来源信息 -->
          <div v-if="wordData.belongBook" class="word-source">
            <el-tag size="small" type="info">{{ wordData.belongBook }}</el-tag>
          </div>
          <div class="pronunciation">
            <button class="pronunciation-switch" @click="switchPhoneType">
              {{ phoneType === 0 ? '美' : '英' }}
            </button>
            <span class="phone-text" @click="playPronunciation">{{ currentPhone }}</span>
            <el-button @click="playPronunciation" type="text" icon="el-icon-video-play" class="play-btn">
              播放
            </el-button>
          </div>
        </div>
          <!-- 词义 -->
        <div class="translations-section">
          <div class="section-title">词义</div>
          <div class="translations-grid">
            <div v-for="(translation, index) in wordData.translations" :key="index" class="translation-group">
              <div class="word-type-tag">{{ translation.wordType }}</div>
              <div class="meanings-list">
                <span class="meaning-text">{{ translation.cnTran }}</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 常用短语 -->
        <div v-if="wordData.phrases && wordData.phrases.length > 0" class="phrases-section">
          <div class="section-title">常用短语</div>
          <div class="phrases-list">
            <div v-for="(phrase, index) in wordData.phrases" :key="index" class="phrase-group">
              <div class="phrase-en">{{ phrase.enPhrase }}</div>
              <div class="phrase-cn">{{ phrase.cnPhrase }}</div>
            </div>
          </div>
        </div>
        
        <!-- 例句 -->
        <div v-if="wordData.sentences && wordData.sentences.length > 0" class="sentences-section">
          <div class="section-title">例句</div>
          <div class="sentences-list">
            <div v-for="(sentence, index) in wordData.sentences" :key="index" class="sentence-group">
              <div class="sentence-en">{{ sentence.enSentence }}</div>
              <div class="sentence-cn">{{ sentence.cnSentence }}</div>
            </div>
          </div>
        </div>          <!-- 记忆方法 -->
        <div v-if="wordData.remMethod" class="memory-section">
          <div class="section-title">记忆方法</div>
          <div class="memory-text">{{ wordData.remMethod }}</div>
        </div>
        
        <!-- 用户记忆信息 -->
        <div v-if="wordData.userMemory" class="user-memory-section">
          <div class="section-title">学习记录</div>
          <div class="memory-stats-compact">
            <div class="memory-progress">
              <div class="progress-info">
                <span class="progress-label">掌握程度</span>
                <span class="progress-text">{{ getMemoryLevelText() }}</span>
              </div>
              <div class="progress-bar">
                <div 
                  class="progress-fill" 
                  :style="{ width: getMemoryPercentage() + '%' }"
                  :class="getMemoryLevelClass()"
                ></div>
              </div>
            </div>
            <div class="stats-row">              <div class="stat-compact" v-if="wordData.userMemory.learnedCount > 0">
                <span class="stat-value">{{ wordData.userMemory.learnedCount }}</span>
                <span class="stat-label">次学习</span>
              </div>
              <div class="stat-compact" v-if="wordData.userMemory.lastLearnTime">
                <span class="stat-value">{{ formatLearnTime(wordData.userMemory.lastLearnTime) }}</span>
                <span class="stat-label">上次学习</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button 
            v-if="!wordData.userMemory || !wordData.userMemory.isLearned" 
            @click="addToStudyList" 
            type="success" 
            icon="el-icon-plus"
          >
            加入学习计划
          </el-button>
          <el-button 
            v-else
            @click="reviewWord" 
            type="warning" 
            icon="el-icon-refresh"
          >
            复习这个单词
          </el-button>
          <el-button @click="goBack" type="primary" icon="el-icon-back">
            返回
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 音频播放器 -->
    <audio ref="audioPlayer" :src="audioUrl"></audio>
  </div>
</template>

<script>
import Header from "@/components/Header.vue";
import request from "@/utils/request.js";

export default {
  name: "WordDetail",
  components: {
    Header
  },
  data() {
    return {
      wordData: null,
      loading: true,
      error: false,
      errorMessage: "",
      phoneType: 0, // 0: 美音, 1: 英音
      userImageUrl: this.$store.getters.userImageUrl,
      returnRoute: null // 用于存储返回路由信息
    };
  },
  computed: {
    wordText() {
      return this.$route.params.word || "";
    },
    currentPhone() {
      if (!this.wordData) return "";
      return this.phoneType === 0 ? this.wordData.usPhone : this.wordData.ukPhone;
    },
    audioUrl() {
      if (!this.wordText) return "";
      return `http://dict.youdao.com/dictvoice?type=${this.phoneType}&audio=${this.wordText}`;
    }
  },
  created() {
    // 保存返回路由信息
    this.returnRoute = this.$route.query.from || '/english-chat';
    this.fetchWordDetail();
  },
  methods: {    async fetchWordDetail() {
      try {
        this.loading = true;
        this.error = false;
        
        const word = this.wordText;
        if (!word) {
          throw new Error('单词参数无效');
        }
        
        // 获取用户信息
        const userJson = localStorage.getItem("user");
        if (!userJson) {
          throw new Error('请先登录');
        }
        const user = JSON.parse(userJson);
        
        // 方案1：先尝试从用户的学习计划中查找单词（新单词和复习单词）
        let foundInPlan = false;
        
        // 1.1 从新单词列表中查找
        try {
          const newWordsResponse = await request.get('/memory/newWords', {
            params: {
              userID: user.userID,
              needCount: 100 // 获取较多单词以便找到目标单词
            }
          });
          
          if (newWordsResponse && newWordsResponse.data && Array.isArray(newWordsResponse.data)) {
            const targetWord = newWordsResponse.data.find(wordItem => 
              wordItem.word && wordItem.word.toLowerCase() === word.toLowerCase()
            );
            
            if (targetWord) {
              this.wordData = targetWord;
              // 这是新单词，用户还没学过
              this.wordData.userMemory = {
                isLearned: false,
                strangeDegree: 3, // 新单词默认陌生度最高
                learnedCount: 0,
                lastLearnTime: null
              };
              foundInPlan = true;
            }
          }
        } catch (error) {
          console.warn('获取新单词列表失败:', error);
        }
        
        // 1.2 如果在新单词中没找到，尝试从复习单词中查找
        if (!foundInPlan) {
          try {
            const reviewResponse = await request.get('/memory/reviewWords', {
              params: {
                userID: user.userID
              }
            });
            
            if (reviewResponse && reviewResponse.data && Array.isArray(reviewResponse.data)) {
              const reviewTargetWord = reviewResponse.data.find(wordItem => 
                wordItem.word && wordItem.word.toLowerCase() === word.toLowerCase()
              );
                if (reviewTargetWord) {
                this.wordData = reviewTargetWord;
                // 标记这是已学习的单词
                this.wordData.userMemory = {
                  isLearned: true,
                  strangeDegree: reviewTargetWord.strangeDegree !== undefined ? reviewTargetWord.strangeDegree : 2,
                  learnedCount: Math.max(1, (3 - (reviewTargetWord.strangeDegree !== undefined ? reviewTargetWord.strangeDegree : 2))), // 根据陌生度估算学习次数
                  lastLearnTime: new Date().toISOString()
                };
                foundInPlan = true;
              }
            }
          } catch (error) {
            console.warn('获取复习单词列表失败:', error);
          }
        }
          // 方案2：如果在学习计划中没找到，尝试通过通用API获取单词信息
        if (!foundInPlan) {
          try {
            const wordDetailResponse = await request.get('/word/search', {
              params: {
                word: word,
                userID: user.userID
              }
            });
              if (wordDetailResponse && wordDetailResponse.code === "0" && wordDetailResponse.data) {
              const apiData = wordDetailResponse.data;
              
              console.log('API返回的单词数据:', apiData);
              console.log('陌生度值:', apiData.strangeDegree);
              
              // 转换API数据格式以适应组件期望的格式
              this.wordData = {
                wordID: apiData.wordID,
                word: apiData.word,
                usPhone: apiData.usPhone,
                ukPhone: apiData.ukPhone,
                remMethod: apiData.remMethod,
                picUrl: apiData.picUrl,
                belongBook: apiData.belongBook,
                // 转换translations格式
                translations: apiData.translations ? apiData.translations.map(trans => ({
                  wordType: trans.enTran || trans.wordType, // 使用enTran作为词性
                  cnTran: trans.cnTran
                })) : [],
                // 保持phrases和sentences格式不变
                phrases: apiData.phrases || [],
                sentences: apiData.sentences || [],                // 设置用户记忆信息
                userMemory: {
                  isLearned: false,
                  strangeDegree: apiData.strangeDegree !== undefined ? apiData.strangeDegree : 3,
                  learnedCount: 0,
                  lastLearnTime: null,
                  inPlan: false, // 标记不在学习计划中
                  fromAPI: true // 标记来源于API查询
                }
              };
              foundInPlan = true;
            }
          } catch (error) {
            console.warn('通用单词查询失败:', error);
          }
        }
        
        // 方案3：如果所有API都失败，使用模拟数据（仅用于演示）
        if (!foundInPlan) {
          // 创建一个基本的单词数据结构
          this.wordData = {
            word: word,
            wordID: null,
            usPhone: `/${word}/`, // 简单的音标占位符
            ukPhone: `/${word}/`,
            translations: [
              {
                wordType: "n.",
                cnTran: "暂无释义信息"
              }
            ],
            phrases: [],
            sentences: [],
            remMethod: null,
            userMemory: {
              isLearned: false,
              strangeDegree: 3,
              learnedCount: 0,
              lastLearnTime: null,
              inPlan: false,
              noData: true // 标记为无数据状态
            }
          };
        }
        
      } catch (error) {
        console.error('获取单词详情失败:', error);
        this.error = true;
        this.errorMessage = error.message || '网络请求失败，请稍后重试';
      } finally {
        this.loading = false;
      }
    },
    
    switchPhoneType() {
      this.phoneType = this.phoneType === 0 ? 1 : 0;
      // 切换后自动播放
      this.$nextTick(() => {
        this.playPronunciation();
      });
    },
    
    playPronunciation() {
      if (this.$refs.audioPlayer) {
        this.$refs.audioPlayer.play();
      }
    },
    
    retryQuery() {
      this.fetchWordDetail();
    },    addToStudyList() {
      // 使用和背单词界面相同的API添加到学习计划
      const userJson = localStorage.getItem("user");
      if (!userJson) {
        this.$message.error('请先登录');
        return;
      }
      
      const user = JSON.parse(userJson);
      
      // 检查是否有有效的wordID
      if (!this.wordData.wordID) {
        this.$message.error('该单词无法加入学习计划（缺少单词ID）');
        return;
      }
      
      // 使用与 Learning1.vue 中 updateLearningRequest 相同的API
      request.post('/memory/newWord', {
        userID: user.userID,
        wordID: this.wordData.wordID
      })
      .then(res => {
        if (res && res.code === "0") {
          this.$message.success('已加入学习计划');
          // 更新用户记忆信息
          if (this.wordData.userMemory) {
            this.wordData.userMemory.inPlan = true;
            this.wordData.userMemory.isLearned = false;
          }
        } else {
          this.$message.error(res.msg || res.message || '加入学习计划失败');
        }
      })
      .catch(error => {
        console.error('加入学习计划失败:', error);
        this.$message.error('加入学习计划失败，请稍后重试');
      });
    },
      reviewWord() {
      // 复习单词功能
      const userJson = localStorage.getItem("user");
      if (!userJson) {
        this.$message.error('请先登录');
        return;
      }
      
      const user = JSON.parse(userJson);
      
      // 检查是否有有效的wordID
      if (!this.wordData.wordID) {
        this.$message.error('该单词无法进行复习（缺少单词ID）');
        return;
      }
      
      // 使用与 Learning1.vue 中相同的API（但这里是复习单词的逻辑）
      request.put('/memory/reviewWord', {
        userID: user.userID,
        wordID: this.wordData.wordID
      })
      .then(res => {
        if (res && res.code === "0") {
          this.$message.success('复习记录已更新');
          // 更新用户记忆信息
          if (this.wordData.userMemory) {
            this.wordData.userMemory.learnedCount = (this.wordData.userMemory.learnedCount || 0) + 1;
            this.wordData.userMemory.lastLearnTime = new Date().toISOString();
            // 可能降低陌生度
            if (this.wordData.userMemory.strangeDegree > 0) {
              this.wordData.userMemory.strangeDegree = Math.max(0, this.wordData.userMemory.strangeDegree - 1);
            }
          }
        } else {
          this.$message.error(res.msg || res.message || '复习失败');
        }
      })
      .catch(error => {
        console.error('复习失败:', error);
        this.$message.error('复习失败，请稍后重试');
      });
    },    getMemoryPercentage() {
      if (!this.wordData.userMemory || this.wordData.userMemory.strangeDegree === undefined || this.wordData.userMemory.strangeDegree === null) {
        console.log('记忆数据为空或陌生度未定义');
        return 0;
      }
      // strangeDegree范围通常是0-3，0表示完全掌握，3表示陌生
      // 转换为百分比：3->0%, 2->25%, 1->50%, 0->100%
      const degree = this.wordData.userMemory.strangeDegree;
      const percentage = Math.max(0, (3 - degree) * 33.33);
      console.log(`陌生度: ${degree}, 掌握百分比: ${percentage}%`);
      return percentage;
    },
    
    getMemoryLevelClass() {
      const percentage = this.getMemoryPercentage();
      if (percentage >= 75) return 'level-mastered';
      if (percentage >= 50) return 'level-familiar';
      if (percentage >= 25) return 'level-learning';
      return 'level-new';
    },
    
    getMemoryLevelText() {
      const percentage = this.getMemoryPercentage();
      if (percentage >= 75) return '已掌握';
      if (percentage >= 50) return '较熟悉';
      if (percentage >= 25) return '学习中';
      return '陌生';
    },
    
    formatLearnTime(timestamp) {
      if (!timestamp) return '未知';
      
      const date = new Date(timestamp);
      const now = new Date();
      const diffTime = now - date;
      const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
      
      if (diffDays === 0) {
        return '今天';
      } else if (diffDays === 1) {
        return '昨天';
      } else if (diffDays < 7) {
        return `${diffDays}天前`;
      } else {
        return date.toLocaleDateString();
      }
    },
      goBack() {
      // 根据来源页面返回
      if (this.$route.query.from) {
        const returnPath = this.$route.query.from;
        const chatId = this.$route.query.chatId;
        
        // 如果有聊天ID，则带着聊天ID返回
        if (chatId) {
          this.$router.push({
            path: returnPath,
            query: { chatId: chatId }
          });
        } else {
          this.$router.push(returnPath);
        }
      } else {
        this.$router.go(-1);
      }
    }
  }
};
</script>

<style scoped>
.word-detail-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
}

.back-button-container {
  position: fixed;
  top: 80px;
  left: 20px;
  z-index: 1000;
}

.back-btn {
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid #e4e7ed;
  border-radius: 25px;
  padding: 8px 16px;
  color: #606266;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
}

.back-btn:hover {
  background: #409EFF;
  color: white;
  border-color: #409EFF;
}

.word-detail-content {
  padding: 20px;
  margin-top: 60px;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  min-height: calc(100vh - 80px);
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  background: white;
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 15px 35px rgba(50, 50, 93, 0.1), 0 5px 15px rgba(0, 0, 0, 0.07);
}

.spinner {
  width: 50px;
  height: 50px;
  border: 5px solid rgba(94, 114, 228, 0.2);
  border-radius: 50%;
  border-top-color: #5e72e4;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.error-icon {
  font-size: 60px;
  margin-bottom: 20px;
}

.word-detail-panel {
  width: 100%;
  max-width: 800px;
  background: white;
  border-radius: 20px;
  padding: 32px;
  box-shadow: 0 15px 35px rgba(50, 50, 93, 0.1), 0 5px 15px rgba(0, 0, 0, 0.07);
  animation: slideUp 0.5s ease;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.word-header {
  text-align: center;
  margin-bottom: 32px;
  padding-bottom: 24px;
  border-bottom: 1px solid #e2e8f0;
}

.word-text {
  font-size: 48px;
  margin-bottom: 20px;
  color: #32325d;
  letter-spacing: 2px;
  font-weight: 600;
}

.word-source {
  margin-bottom: 15px;
  text-align: center;
}

.word-source .el-tag {
  font-size: 12px;
  padding: 4px 12px;
}

.pronunciation {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 15px;
  margin-top: 20px;
}

.pronunciation-switch {
  background: #5e72e4;
  color: white;
  border: none;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  font-size: 16px;
  cursor: pointer;
  transition: background 0.3s ease;
}

.pronunciation-switch:hover {
  background: #4a5cd0;
}

.phone-text {
  font-size: 20px;
  color: #525f7f;
  cursor: pointer;
  font-family: 'Lucida Console', monospace;
}

.phone-text:hover {
  color: #5e72e4;
  text-decoration: underline;
}

.play-btn {
  color: #5e72e4;
}

.translations-section,
.phrases-section,
.sentences-section,
.memory-section,
.user-memory-section {
  margin-bottom: 24px;
}

.section-title {
  color: #5e72e4;
  font-size: 18px;
  margin-bottom: 12px;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.section-title::before {
  content: '';
  width: 3px;
  height: 18px;
  background: #5e72e4;
  margin-right: 8px;
  border-radius: 2px;
}

/* 词义部分优化 */
.translations-grid {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.translation-group {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.word-type-tag {
  background: #5e72e4;
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  min-width: 40px;
  text-align: center;
  flex-shrink: 0;
  margin-top: 2px;
}

.meanings-list {
  flex: 1;
}

.meaning-text {
  font-size: 16px;
  color: #32325d;
  line-height: 1.6;
}

/* 短语部分优化 */
.phrases-list {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 12px;
}

.phrase-group {
  padding: 12px;
  background: #f8f9fe;
  border-radius: 8px;
  border-left: 3px solid #5e72e4;
}

.phrase-en {
  font-size: 15px;
  color: #32325d;
  margin-bottom: 4px;
  font-weight: 500;
}

.phrase-cn {
  font-size: 14px;
  color: #6c757d;
  margin: 0;
}

/* 例句部分优化 */
.sentences-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.sentence-group {
  padding: 12px;
  background: #f8f9fe;
  border-radius: 8px;
  border-left: 3px solid #28a745;
}

.sentence-en {
  font-size: 15px;
  color: #32325d;
  margin-bottom: 4px;
  font-weight: 500;
  line-height: 1.5;
}

.sentence-cn {
  font-size: 14px;
  color: #6c757d;
  margin: 0;
  line-height: 1.4;
}

/* 记忆方法优化 */
.memory-text {
  background: #fff3cd;
  padding: 12px 16px;
  border-radius: 8px;
  border-left: 3px solid #ffc107;
  font-size: 15px;
  color: #856404;
  line-height: 1.5;
}

/* 学习记录优化 */
.user-memory-section {
  background: linear-gradient(135deg, #f8f9fe 0%, #e8ecf7 100%);
  padding: 16px;
  border-radius: 12px;
  border: 1px solid #e2e8f0;
}

.memory-stats-compact {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.memory-progress {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.progress-label {
  font-size: 14px;
  color: #6c757d;
  font-weight: 500;
}

.progress-text {
  font-size: 14px;
  font-weight: 600;
}

.progress-bar {
  width: 100%;
  height: 6px;
  background: #e2e8f0;
  border-radius: 3px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  border-radius: 3px;
  transition: width 0.3s ease;
}

.stats-row {
  display: flex;
  gap: 20px;
}

.stat-compact {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.stat-compact .stat-value {
  font-size: 18px;
  font-weight: 600;
  color: #32325d;
  line-height: 1;
}

.stat-compact .stat-label {
  font-size: 12px;
  color: #6c757d;
  margin-top: 2px;
}

.level-new {
  background: #fa5252;
}

.level-learning {
  background: #fd7e14;
}

.level-familiar {
  background: #fab005;
}

.level-mastered {
  background: #51cf66;
}

.level-new + .progress-text {
  color: #fa5252;
}

.level-learning + .progress-text {
  color: #fd7e14;
}

.level-familiar + .progress-text {
  color: #fab005;
}

.level-mastered + .progress-text {
  color: #51cf66;
}

.action-buttons {
  margin-top: 32px;
  text-align: center;
  display: flex;
  gap: 12px;
  justify-content: center;
  flex-wrap: wrap;
}

.action-buttons .el-button {
  padding: 12px 25px;
  font-size: 16px;
  border-radius: 25px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .word-detail-panel {
    margin: 10px;
    padding: 20px;
  }
  
  .word-text {
    font-size: 36px;
  }
  
  .pronunciation {
    flex-wrap: wrap;
    gap: 10px;
  }
  
  .translation-group {
    flex-direction: column;
    gap: 6px;
  }
  
  .word-type-tag {
    align-self: flex-start;
  }
  
  .phrases-list {
    grid-template-columns: 1fr;
    gap: 8px;
  }
  
  .stats-row {
    justify-content: space-around;
  }
  
  .action-buttons {
    flex-direction: column;
    align-items: center;
    gap: 10px;
  }
  
  .action-buttons .el-button {
    width: 100%;
    max-width: 200px;
  }
}
</style>
